import Vue from "vue";
import axios from "axios";
import router from "../modules/index/router";

import api from "@/api/api";
import ExportApi from "@/api/ExportApi";
import otherApi from "@/api/otherApi";
import WpsApi from "@/api/WpsApi";
// WebSocket封装方法
import * as socketApi from "@/api/socket";

Vue.prototype.socketApi = socketApi;
Vue.prototype.API = api;
Vue.prototype.ExportApi = ExportApi;
Vue.prototype.otherApi = otherApi;
Vue.prototype.WpsApi = WpsApi;
// Todo 将中断器重构成可配置项
axios.interceptors.request.use(
  function (config) {
    config.headers.token = window.sessionStorage.getItem("token");
    config.headers.userRole = "ADMIN";
    config.headers.version = "1.0.0";
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    // Do something with response error
    if (error.response.status >= 500) {
      const body = JSON.stringify(error.response.data);
      // console.log(error.response.data.message)
      Vue.prototype.$notify.error({
        title: error.response.status,
        dangerouslyUseHTMLString: true,
        // message: `<p class="error-info-block">${error.request.responseURL}</p><p class="error-info-block">${body}</p>`,
        message: ` <p class="error-info-block">服务端异常</p>`,
        duration: 4000,
        position: "bottom-right"
      });
    } else {
      if (error.response.status !== 401) {
        if (error.response.request.responseType === "arraybuffer") {
          let enc = new TextDecoder("utf-8");
          let data = JSON.parse(
            enc.decode(new Uint8Array(error.response.data))
          );
          Vue.prototype.$notify.error({
            title: "错误",
            message: data.message
          });
        } else {
          Vue.prototype.$notify.error({
            title: "错误",
            message: error.response.data.message
          });
        }
        console.log(error);
      }
    }

    if (error.response.status > 400 && error.response.status < 500) {
      if (error.response.status === 401) {
        // window.sessionStorage.setItem("token", "");
        window.sessionStorage.removeItem("token");
      }
      let appKey = window.sessionStorage.getItem("appKey");
      router.push({name: "login"});
    }
    return Promise.reject(error);
  }
);
